package myky.com.doctorapp.utils;

import org.json.JSONObject;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.concurrent.TimeUnit;

import myky.com.doctorapp.api.ApiManager;
import okhttp3.FormBody;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okio.Buffer;
import okio.BufferedSource;

/**
 * @author Mr.li
 */
public class VerifyLoginInterceptor implements Interceptor {
    private static final Charset UTF8 = Charset.forName("UTF-8");

    public VerifyLoginInterceptor() {

    }

    @Override
    public Response intercept(Chain chain) throws IOException {

        Request request = chain.request();
        Response response = chain.proceed(request);
        return toLogin(response,request);
    }


    public Response toLogin(Response responses,Request requests) {

        Response response=null;
        try {
            BufferedSource source = responses.body().source();
            // Buffer the entire body.
            source.request(Long.MAX_VALUE);
            Buffer buffer = source.buffer();
            Charset charset = UTF8;
            MediaType contentType = responses.body().contentType();
            if (contentType != null) {
                charset = contentType.charset(UTF8);
            }
            String string = buffer.clone().readString(charset);
//            ILog.i("第一次请求： "+string);
            JSONObject jsonObject=new JSONObject(string);
            int type = jsonObject.getInt("type");
            OkHttpClient okHttpClient = new OkHttpClient.Builder()
                    .connectTimeout(5000, TimeUnit.MILLISECONDS)
                    .cookieJar(ApiManager.cookieJar)
                    .build();
            //重定向的url
            RequestBody requestBody=new FormBody.Builder()
                    .add("username",ShareUtil.getString(Constants.USERNAME))
                    .add("password",ShareUtil.getString(Constants.PASSWORD))
                    .build();
            //get请求时登录认证过期
            if (type==105){
                if (ShareUtil.getBoolean("isQuickLogin")){
                    RequestBody requestBodyQuick=new FormBody.Builder()
                            .add("smsCode",ShareUtil.getString(Constants.SMSCODE))
                            .add("userphone",ShareUtil.getString(Constants.USERPHONE))
                            .add("smskey",ShareUtil.getString(Constants.SMSKEY))
                            .build();
                    String locationUrl=responses.request().url().toString();
                    Request request=new Request.Builder().url(locationUrl).post(requestBodyQuick).build();
                    response = okHttpClient.newCall(request).execute();
                }else {


                    String locationUrl=responses.request().url().toString();
                    Request request=new Request.Builder().url(locationUrl).post(requestBody).build();
                    response = okHttpClient.newCall(request).execute();
                }
            }
            if (type==112){

                JSONObject payLoad = jsonObject.getJSONObject("payLoad");
                String postUrl = payLoad.getString("authenticateUrl");
                Request postRequest =new Request.Builder().url(postUrl).build();
                Request postRequest2 =new Request.Builder().post(requestBody).url(postUrl).build();
                Response response2 = okHttpClient.newCall(postRequest).execute();
                String string1 = response2.body().string();
                JSONObject jsonObject1=new JSONObject(string1);
                int type1 = jsonObject1.getInt("type");
                if (type1==105){
                    Response response3 = okHttpClient.newCall(postRequest2).execute();
                    String string2=response3.body().string();
                    JSONObject jsonObject2=new JSONObject(string2);
                    int type2=jsonObject2.getInt("type");
                    if (type2==113){
                        response=okHttpClient.newCall(requests).execute();
                    }
                }

            }
        } catch (Exception e) {

            return responses;
        }

        return response!=null?response:responses;

    }
}
